﻿using BuildSystem.MVC.Common;
using BuildSystemApplication.Models.Build;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Linq;

namespace BuildSystemApplication.Controllers
{
    public class SystemController : Controller
    {
        //
        // GET: /QForm/

        public ActionResult BuildForm()
        {
            QFormModel model = new QFormModel();
            model.Category = GetCategoryList("");
            model.Section = GetSectionList("");
            return View(model);
        }

        public ActionResult GetFormSchemaHtml(string section)
        {
            BuildForm formSchema = GetFormSchema(section);
            string htmlOutput = string.Empty;
            div pnlDiv = new div();

            List<object> divItems = new List<object>();
            divItems.Add(string.Format("<h2>{0}</h2>", formSchema.Title));
            divItems.Add(string.Format("<p>{0}</p>", formSchema.Description));

            if (formSchema.Section != null)
            {
                foreach (BuildFormSection formSection in formSchema.Section)
                {
                    divFieldset fieldset = new divFieldset();
                    fieldset.legend = string.Format("<legend>{0}</legend>", formSection.Name);
                    List<divFieldsetLI> fieldLiList = new List<divFieldsetLI>();
                    foreach (BuildFormSectionField sectionField in formSection.FormFields)
                    {
                        divFieldsetLI fieldsetLi = new divFieldsetLI();
                        fieldsetLi.label = new divFieldsetLILabel()
                        {
                            @for = sectionField.Label,
                            Value = sectionField.Label
                        };

                        List<divFieldsetLIInput> inputList = new List<divFieldsetLIInput>();
                        if (sectionField.Type == "text")
                        {
                            inputList.Add(new divFieldsetLIInput()
                            {
                                id = sectionField.ID,
                                name = sectionField.ID,
                                type = "text"
                            });

                            fieldsetLi.input = inputList.ToArray();
                        }
                        else if (sectionField.Type == "textarea")
                        {
                            fieldsetLi.textarea = new divFieldsetLITextarea()
                            {
                                cols = "80",
                                id = sectionField.ID,
                                name = sectionField.ID,
                                rows = "5"
                            };
                        }
                        else if (sectionField.Type == "dropdown")
                        {
                            List<divFieldsetLISelectOption> selectOptions = new List<divFieldsetLISelectOption>();
                            List<string> dropdownValues = GetDropdownValues(sectionField.ID);
                            foreach (var item in dropdownValues)
                            {
                                selectOptions.Add(new divFieldsetLISelectOption()
                                {
                                    value = item,
                                    Value = item,
                                });
                            }

                            fieldsetLi.select = new divFieldsetLISelect()
                            {
                                id = sectionField.ID,
                                name = sectionField.ID
                            };

                            fieldsetLi.select.option = selectOptions.ToArray();
                        }
                        else if (sectionField.Type == "checkbox")
                        {
                            inputList.Clear();
                            List<string> checkboxValues = GetDropdownValues(sectionField.ID);
                            foreach (var item in checkboxValues)
                            {
                                inputList.Add(new divFieldsetLIInput()
                                {
                                    id = sectionField.ID,
                                    name = sectionField.ID,
                                    type = "checkbox",
                                    value = item,
                                    Value = item
                                });
                            }

                            fieldsetLi.input = inputList.ToArray();
                        }
                        else if (sectionField.Type == "radio")
                        {
                            inputList.Clear();
                            List<string> checkboxValues = GetDropdownValues(sectionField.ID);
                            foreach (var item in checkboxValues)
                            {
                                inputList.Add(new divFieldsetLIInput()
                                {
                                    id = sectionField.ID,
                                    name = sectionField.ID,
                                    type = "radio",
                                    value = item,
                                    Value = item
                                });
                            }

                            fieldsetLi.input = inputList.ToArray();
                        }

                        fieldLiList.Add(fieldsetLi);
                    }

                    fieldset.ol = fieldLiList.ToArray();

                    divItems.Add(fieldset);
                }
            }

            pnlDiv.Items = divItems.ToArray();
            htmlOutput = Utility.SerializePnlDiv(pnlDiv);
            htmlOutput = htmlOutput.Replace("&lt;", "<");
            htmlOutput = htmlOutput.Replace("&gt;", ">");
            htmlOutput = htmlOutput.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "");
            htmlOutput = htmlOutput.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");

            return Content(htmlOutput, "text/html");
        }

        private List<string> GetDropdownValues(string dropdownCode)
        {
            List<string> dropdownValues = new List<string>();
            using (BuildSystemEntities dataContext = new BuildSystemEntities())
            {
                var result = dataContext.FieldMasterDatas.Where(obj => (obj.FieldID == dropdownCode));
                dropdownValues.Add("");
                foreach (var item in result)
                {
                    dropdownValues.Add(item.DropdownValue);
                }
            }

            return dropdownValues;
        }

        [HttpPost]
        public ActionResult BuildForm(FormCollection formCollection)
        {
            string loadForm = formCollection["loadForm"];
            string section = this.Request.Form["radSection"];
            BuildForm formSchema = GetFormSchema(section);
            
            QFormModel model = new QFormModel();
            string category = "";
            foreach (string formItem in formCollection)
            {
                if (formItem.Contains("checkCategory"))
                {
                    if (this.Request.Form[formItem] == "true,false")
                    {
                        category += formItem.Split('_')[1] + ";";
                    }
                }
            }

            if (!string.IsNullOrEmpty(category))
            {
                category = category.Remove(category.LastIndexOf(';'));
            }

            model.Category = GetCategoryList(category);
            model.Section = GetSectionList(section);

            if (formSchema != null)
            {
                using (BuildSystemEntities dataContext = new BuildSystemEntities())
                {
                    List<FormData> formDataList = dataContext.FormDatas.Where(obj => (obj.FormID == formSchema.ID)).ToList();
                    if (formDataList.Count > 0)
                    {
                        BuildFormData buildFormData = Utility.DeserializeFormDataXml(formDataList[0].FormDataXml);
                        if (formSchema.Section != null)
                        {
                            foreach (var sectionItem in formSchema.Section)
                            {
                                foreach (var fieldItem in sectionItem.FormFields)
                                {
                                    BuildFormDataField dataField = new BuildFormDataField();
                                    fieldItem.Value = buildFormData.Field.Where(obj => (obj.ID == fieldItem.ID)).ToList()[0].Value;
                                }
                            }
                        }
                    }

                    model.Title = formSchema.Title;
                    model.Description = formSchema.Description;

                    if (loadForm == "")
                    {
                        BuildFormData buildFormData = new BuildFormData();
                        buildFormData.ID = formSchema.ID;
                        List<BuildFormDataField> dataFields = new List<BuildFormDataField>();
                        if (formSchema.Section != null)
                        {
                            foreach (var sectionItem in formSchema.Section)
                            {
                                foreach (var fieldItem in sectionItem.FormFields)
                                {
                                    BuildFormDataField dataField = new BuildFormDataField();
                                    if (fieldItem.Type != "checkbox")
                                    {
                                        dataField.ID = fieldItem.ID;
                                        dataField.Value = formCollection[fieldItem.ID];
                                        fieldItem.Value = formCollection[fieldItem.ID];
                                    }
                                    else
                                    {
                                        string checkvalues = "";
                                        foreach (string formItem in formCollection)
                                        {
                                            if (formItem.Contains(fieldItem.ID))
                                            {
                                                if (this.Request.Form[formItem] == "true,false")
                                                {
                                                    checkvalues += formItem.Split('_')[1] + ";";
                                                }
                                            }
                                        }

                                        if (!string.IsNullOrEmpty(checkvalues))
                                        {
                                            checkvalues = checkvalues.Remove(checkvalues.LastIndexOf(';'));
                                        }

                                        dataField.ID = fieldItem.ID;
                                        dataField.Value = checkvalues;
                                        fieldItem.Value = checkvalues;
                                    }

                                    dataFields.Add(dataField);
                                }
                            }
                        }

                        buildFormData.Field = dataFields.ToArray();

                        if (formDataList.Count == 0)
                        {
                            FormData formData = new FormData();
                            formData.Category = category;
                            formData.FormID = Convert.ToInt32(formSchema.ID);
                            formData.CreatedBy = "demo";
                            formData.CreatedDate = DateTime.Now;
                            formData.FormDataXml = Utility.SerializeFormData(buildFormData);
                            formData.Section = section;
                            dataContext.FormDatas.Add(formData);
                        }
                        else
                        {
                            formDataList[0].FormDataXml = Utility.SerializeFormData(buildFormData);
                            formDataList[0].Section = section;
                            formDataList[0].Category = category;
                        }

                        dataContext.SaveChanges();
                    }
                }

                model.FormSchemaXml = formSchema;
            }

            return View(model);
        }

        //[HttpPost]
        //public ActionResult QForm(string section)
        //{

        //    return View();
        //}

        private Dictionary<string, bool> GetCategoryList(string selectedValue)
        {
            Dictionary<string, bool> result = new Dictionary<string, bool>();
            List<string> selectedCategoryList = selectedValue.Split(';').ToList();
            using (BuildSystemEntities dataContext = new BuildSystemEntities())
            {
                List<Category> categoryList = dataContext.Categories.ToList();
                foreach (var item in categoryList)
                {
                    bool isValueSelected = false;
                    if (selectedCategoryList.Contains(item.CategoryName))
                    {
                        isValueSelected = true;
                    }

                    result.Add(item.CategoryName, isValueSelected);
                }
            }

            return result;
        }

        private Dictionary<string, bool> GetSectionList(string selectedValue)
        {
            Dictionary<string, bool> result = new Dictionary<string, bool>();
            using (BuildSystemEntities dataContext = new BuildSystemEntities())
            {
                List<Section> sectionList = dataContext.Sections.ToList();
                foreach (var item in sectionList)
                {
                    bool isValueSelected = false;
                    if (selectedValue == item.SectionName)
                    {
                        isValueSelected = true;
                    }

                    result.Add(item.SectionName, isValueSelected);
                }
            }

            return result;
        }

        private BuildForm GetFormSchema(string sectionName)
        {
            BuildForm formSchema = null;
            using (BuildSystemEntities dataContext = new BuildSystemEntities())
            {
                string schemaXml = string.Empty;
                var result = dataContext.GetFormSchema(sectionName);
                foreach (var item in result)
                {
                    schemaXml = item.SchemaXml;
                }

                if (schemaXml != null)
                {
                    formSchema = Utility.DeserializeFormSchemaXml(schemaXml);
                }
            }

            return formSchema;
        }

      
    }
}
